package com.ttg.web.service.Impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.CaseFormat;
import com.ttg.common.constant.BasicConstant;
import com.ttg.common.constant.ParentDateTypeConstant;
import com.ttg.common.dto.*;
import com.ttg.common.entities.BaseResult;
import com.ttg.common.entities.RattingTask;
import com.ttg.common.enums.*;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.common.utils.QxAndJhUtil;
import com.ttg.model.dto.excel.*;
import com.ttg.model.pojo.*;
import com.ttg.web.dao.*;
import com.ttg.web.manage.GetBankFileTypeObjectManage;
import com.ttg.web.service.GradeToCouponService;
import com.ttg.web.service.ManageTagInfoService;
import com.ttg.web.utils.NextUpdateTimeUtil;
import jxl.CellType;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangHongYuan
 * @description
 * @date 2024/1/23 10:51
 */
@Service
@Slf4j
public class ManageTagInfoServiceImpl implements ManageTagInfoService {

    @Autowired
    private TagInfoDao tagInfoDao;
    @Autowired
    private TblTagInfoDao tblTagInfoDao;
    @Autowired
    private GradeToCouponService gradeToCouponService;
    @Autowired
    private ConditionsInfoDao conditionsInfoDao;

    @Autowired
    private ConditionsNameDao conditionsNameDao;

    @Autowired
    private BankInfoDao bankInfoDao;

    @Autowired
    private VipInfoDao vipInfoDao;

    @Autowired
    private PrimitiveBankInfoDao primitiveBankInfoDao;

    @Autowired
    private PrivatePrimitiveDao privatePrimitiveDao;

    @Autowired
    private PublicPrimitiveDao publicPrimitiveDao;

    @Autowired
    private VipAccountCountInfoDao vipAccountCountInfoDao;

    @Autowired
    private VipBindTagDao vipBindTagDao;

    @Autowired
    private VipBindTagBackUpDao vipBindTagBackUpDao;

    @Autowired
    private BankPublicPrimitiveDao bankPublicPrimitiveDao;

    @Autowired
    private BankPrivatePrimitiveDao bankPrivatePrimitiveDao;

    @Autowired
    private BankCustomerInfoDao bankCustomerInfoDao;

    @Autowired
    private BankCardDataInfoDao bankCardDataInfoDao;

    @Autowired
    private BankProductDataInfoDao bankProductDataInfoDao;

    @Autowired
    private BankCustomerSignInfoDao bankCustomerSignInfoDao;

    @Autowired
    private BankCardBindingInfoDao bankCardBindingInfoDao;

    @Autowired
    private BankPublicTradePrimitiveDao bankPublicTradePrimitiveDao;

    @Autowired
    private VipBindMerchantDao vipBindMerchantDao;

    @Value("${autotask.pageSize}")
    private Integer pageSize;

    @Autowired
    private TagHisDao tagHisDao;

    public ParentDateTypeConstant getParentDateTypeConstant(Long dataTypeId) {
        if (ConditionsDataTypeEnum.TYPE_NUMBER.getValue() == dataTypeId) {
            return new NumberDataType();
        } else if (ConditionsDataTypeEnum.TYPE_STRING.getValue() == dataTypeId) {
            return new StringDataType();
        } else if (ConditionsDataTypeEnum.TYPE_BOOLEAN.getValue() == dataTypeId) {
            return new BooleanDataType();
        } else if (ConditionsDataTypeEnum.TYPE_DATE.getValue() == dataTypeId) {
            return new DateDataType();
        } else if (ConditionsDataTypeEnum.TYPE_STRING_VAGUE.getValue() == dataTypeId) {
            return new StringVagueDataType();
        }
        return null;
    }

    @RattingTask(taskEnum = TaskEnum.VIP_TAG_BIND)
    @Override
    public void vipTagBind() {
        List<TblTagInfo> list = tblTagInfoDao.getAllByTypeAndStatus(TagDataSourceEnum.USER);
        for (TblTagInfo tagInfo : list) {
            //1.检查当前时间>=下次更新时间，满足才本次更新
            LocalDateTime updateTime = tagInfo.getTagNextUpdateTime();
            LocalDateTime now = LocalDateTime.now();
            if (!(now.compareTo(updateTime) >= 0)) {
                continue;
            }
            tagInfo.setVersionStatus(VersionStatusEnum.PROCESSING.getCode());

            TagInfo tagInfos = new TagInfo();
            BeanUtils.copyProperties(tagInfo, tagInfos);
            Integer tagHisId = addTagHis(tagInfos);
            try {
                //2.根据更新频率计算下次更新时间，保存到标签表
                LocalDateTime nextUpdateTime = NextUpdateTimeUtil.nextUpdateTime(tagInfo);
                List<ConditionsInfo> byTagId = conditionsInfoDao.findByTagId(tagInfo.getId());
                asyncUpdateVipTag(tagInfo.getId(), byTagId, nextUpdateTime, tagHisId);
            } catch (Exception e) {
                updateTagHis(tagInfos, tagHisId, VersionStatusEnum.FAIL.getCode(),null);
                log.error("vipTagBind error", e);
            }
        }
    }


    @RattingTask(taskEnum = TaskEnum.MCT_TAG_BIND)
    @Override
    public void mctTagBind() {
        List<TagInfo> list = tagInfoDao.getAllByTypeAndStatus(TagTypeEnum.TYPE_PUBLIC);
        for (TagInfo tagInfo : list) {
            boolean flag = false;
            Integer updateDate = tagInfo.getUpdateDate();
            LocalDateTime updateTime = tagInfo.getUpdateTime();

            if (Objects.isNull(updateTime)) {
                continue;
            }
            LocalDate now = LocalDate.now();
            LocalDate date = updateTime.toLocalDate();
            LocalDate plusDays = null;
            switch (updateDate) {
                case 1:
                    flag = true;
                    break;
                case 2:
                    plusDays = date.plusWeeks(1);
                    if (now.compareTo(plusDays) >= 0) {
                        flag = true;
                    }
                    break;
                case 3:
                    plusDays = date.plusMonths(1);
                    if (now.compareTo(plusDays) >= 0) {
                        flag = true;
                    }
                    break;
                case 4:
                    plusDays = date.plusMonths(3);
                    if (now.compareTo(plusDays) >= 0) {
                        flag = true;
                    }
                    break;
                case 5:
                    plusDays = date.plusYears(1);
                    if (now.compareTo(plusDays) >= 0) {
                        flag = true;
                    }
                    break;
                default:
                    break;
            }
            if (!flag) {
                continue;
            }

            tagInfo.setVersionStatus(VersionStatusEnum.PROCESSING.getCode());
            Integer tagHisId = addTagHis(tagInfo);
            try {
                List<ConditionsInfo> byTagId = conditionsInfoDao.findByTagId(tagInfo.getId());
                asyncUpdateMctTag(tagInfo.getId(), byTagId, LocalDateTime.now(), tagHisId);
            } catch (Exception e) {
                updateTagHis(tagInfo, tagHisId, VersionStatusEnum.FAIL.getCode(),null);
                log.error("mctTagBind error", e);
            }
        }
    }


    public String getObjectFieldValue(Object obj, String key) {
        log.info("【ManageTagInfoServiceImpl getObjectFieldValue】start===>{},{}", obj, key);
        String res = "";
        try {
            Field field = obj.getClass().getDeclaredField(key);
            field.setAccessible(true);
            Object o = field.get(obj);
            if (Objects.nonNull(o)) {
                res = o + "";
                if (o instanceof LocalDateTime) {
                    res = DateTimeUtil.formatYYYY_MM_DD_HH_MM_SS((LocalDateTime) o);
                }
                if (o instanceof LocalDate) {
                    res = DateTimeUtil.formatYYYY_MM_DD((LocalDate) o);
                }
                log.info("【ManageTagInfoServiceImpl getObjectFieldValue】end===>{}", o);
                return res;
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("【ManageTagInfoServiceImpl getObjectFieldValue】", e);
        }
        return res;
    }


//    public void  getDataByPrivateFile(String filePath){
//
//        List<PrivatePrimitiveExcelDto> privatePrimitiveExcelDtos = readExcelData(filePath, 0, PrivatePrimitiveExcelDto.class);
//        privatePrimitiveExcelDtos.forEach(p->{
//            PrivatePrimitive primitiveBankInfo =new PrivatePrimitive();
//            //参数检查
//            BeanUtils.copyProperties(p,primitiveBankInfo);
//            privatePrimitiveDao.save(primitiveBankInfo);
//        });
//
//
//    }

    public void getDataByFileTwo(String filePath, Integer type) {
        log.info("【ManageTagInfoServiceImpl.getDataByFileTwo】start==>{},{}", filePath, type);
        for (BankFileTypeEnum value : BankFileTypeEnum.values()) {
            if (!value.getType().equals(type)) {
                continue;
            }

            switch (value) {
                case BANK_CUSTOMER_INFO:
                    List<BankCustomerInfoExcelDto> bankCustomerInfoExcelDtos = readExcel(filePath, value.getSheetIndex(), BankCustomerInfoExcelDto.class);
                    List<VipInfo> vipInfos = new ArrayList<>();
                    for (BankCustomerInfoExcelDto bankCustomerInfoExcelDto : bankCustomerInfoExcelDtos) {
                        if (StringUtils.isEmpty(bankCustomerInfoExcelDto.getCstId())) {
                            continue;
                        }
                        VipInfo byCstId = vipInfoDao.getByCstId(bankCustomerInfoExcelDto.getCstId());
//                        BankCustomerInfo bankCustomerInfoByCstId = bankCustomerInfoDao.getBankCustomerInfoByCstId(bankCustomerInfoExcelDto.getCstId());
//                        BankCustomerInfo bankCustomerInfo = new BankCustomerInfo();
//                        BeanUtils.copyProperties(bankCustomerInfoExcelDto, bankCustomerInfo);
                        VipInfo vipInfo = new VipInfo();
                        vipInfo.setVipCstId(bankCustomerInfoExcelDto.getCstId());
                        vipInfo.setVipCstName(bankCustomerInfoExcelDto.getCstName());
                        vipInfo.setVipIdCardNo(bankCustomerInfoExcelDto.getIdCardNo());
                        vipInfo.setVipPhoneNumber(bankCustomerInfoExcelDto.getPhoneNumber());
                        vipInfo.setVipAge(bankCustomerInfoExcelDto.getAge());
                        vipInfo.setVipSex(bankCustomerInfoExcelDto.getSex());
                        vipInfo.setVipOccupation(bankCustomerInfoExcelDto.getOccupation());
                        vipInfo.setVipAddress(bankCustomerInfoExcelDto.getAddress());
                        vipInfo.setVipRegTime(LocalDateTime.now());
                        vipInfo.setVipRegType(0);
                        vipInfo.setVipStatus(0);
//                                vipInfo.setVipGrade();
//                                vipInfo.setVipGradeStartDate();
//                                vipInfo.setVipGradeDate();
//                                vipInfo.setVipIntegrationAmount();
//                                vipInfo.setVipBindMtcNum();
//                                vipInfo.setVipBindAccountNum();
//                                vipInfo.setVipAgoGrow();
//                                vipInfo.setVipNowGrow();
                        vipInfo.setUpdateTime(LocalDateTime.now());
                        if (!Objects.isNull(byCstId)) {
                            vipInfo.setVipId(byCstId.getVipId());
                        }
                        vipInfos.add(vipInfo);
                        if (vipInfos.size() == 1000) {
                            vipInfoDao.saveOrUpdateBatch(vipInfos);
                            vipInfos.clear();
                        }


                    }
                    if (!CollectionUtils.isEmpty(vipInfos)) {
                        vipInfoDao.saveOrUpdateBatch(vipInfos);
                    }
                    break;
                case BANK_PRIVATE_PRIMITIVE:

                    List<BankPrivatePrimitiveExcelDto> bankPrivatePrimitiveExcelDtos = readExcel(filePath, value.getSheetIndex(), BankPrivatePrimitiveExcelDto.class);
                    List<BankPrivatePrimitive> bankPrivatePrimitives = new ArrayList<>();
                    for (BankPrivatePrimitiveExcelDto bankPrivatePrimitiveExcelDto : bankPrivatePrimitiveExcelDtos) {
                        if (StringUtils.isEmpty(bankPrivatePrimitiveExcelDto.getCstId())) {
                            return;
                        }
                        BankPrivatePrimitive bankPrivatePrimitive = new BankPrivatePrimitive();
                        BeanUtils.copyProperties(bankPrivatePrimitiveExcelDto, bankPrivatePrimitive);

                        bankPrivatePrimitives.add(bankPrivatePrimitive);

                        if (bankPrivatePrimitives.size() == 1000) {
                            bankPrivatePrimitiveDao.saveBatch(bankPrivatePrimitives);
                            bankPrivatePrimitives.clear();
                        }
                    }

                    if (!CollectionUtils.isEmpty(bankPrivatePrimitives)) {
                        bankPrivatePrimitiveDao.saveBatch(bankPrivatePrimitives);
                    }

                    break;
                case BANK_PRIVATE_LUM:
                    break;
                case BANK_CARD_DATA_INFO:
                    List<BankCardDataInfoExcelDto> bankCardDataInfos = readExcel(filePath, value.getSheetIndex(), BankCardDataInfoExcelDto.class);
                    List<BankCardDataInfo> bankCardDataInfoList = new ArrayList<>();
                    for (BankCardDataInfoExcelDto bankCardDataInfoExcelDto : bankCardDataInfos) {
                        if (StringUtils.isEmpty(bankCardDataInfoExcelDto.getCstId())) {
                            return;
                        }
                        BankCardDataInfo bankCardDataInfo = new BankCardDataInfo();
                        BeanUtils.copyProperties(bankCardDataInfoExcelDto, bankCardDataInfo);
                        bankCardDataInfoList.add(bankCardDataInfo);

                        if (bankCardDataInfoList.size() == 1000) {
                            bankCardDataInfoDao.saveBatch(bankCardDataInfoList);
                            bankCardDataInfoList.clear();
                        }
                    }
                    if (!CollectionUtils.isEmpty(bankCardDataInfoList)) {
                        bankCardDataInfoDao.saveBatch(bankCardDataInfoList);
                    }
                    break;
                case BANK_PRODUCT_DATA_INFO:
                    List<BankProductDataInfoExcelDto> addBankProductDataInfoList = readExcel(filePath, value.getSheetIndex(), BankProductDataInfoExcelDto.class);
                    List<BankProductDataInfo> bankProductDataInfos = new ArrayList<>();
                    for (BankProductDataInfoExcelDto bankProductDataInfoExcelDto : addBankProductDataInfoList) {
                        if (StringUtils.isEmpty(bankProductDataInfoExcelDto.getCstId())) {
                            return;
                        }

                        BankProductDataInfo bankProductDataInfo = new BankProductDataInfo();
                        BeanUtils.copyProperties(bankProductDataInfoExcelDto, bankProductDataInfo);
                        bankProductDataInfos.add(bankProductDataInfo);

                        if (bankProductDataInfos.size() == 1000) {
                            bankProductDataInfoDao.saveBatch(bankProductDataInfos);
                            bankProductDataInfos.clear();
                        }
                    }
                    if (!CollectionUtils.isEmpty(bankProductDataInfos)) {
                        bankProductDataInfoDao.saveBatch(bankProductDataInfos);
                    }
                    break;
                case BANK_CUSTOMER_SIGN_INFO:
                    List<BankCustomerSignInfoExcelDto> addBankCustomerSignInfoList = readExcel(filePath, value.getSheetIndex(), BankCustomerSignInfoExcelDto.class);

                    List<BankCustomerSignInfo> bankCustomerSignInfos = new ArrayList<>();

                    for (BankCustomerSignInfoExcelDto bankCustomerSignInfoExcelDto : addBankCustomerSignInfoList) {
                        BankCustomerSignInfo bankCustomerSignInfo = new BankCustomerSignInfo();

                        BeanUtils.copyProperties(bankCustomerSignInfoExcelDto, bankCustomerSignInfo);

                        bankCustomerSignInfos.add(bankCustomerSignInfo);

                        if (bankCustomerSignInfos.size() == 1000) {
                            bankCustomerSignInfoDao.saveBatch(bankCustomerSignInfos);
                            bankCustomerSignInfos.clear();
                        }
                    }
                    if (!CollectionUtils.isEmpty(bankCustomerSignInfos)) {
                        bankCustomerSignInfoDao.saveBatch(bankCustomerSignInfos);
                    }
                    break;
                case BANK_CARD_BINDING_INFO:
                    List<BankCardBindingInfoExcelDto> addBankCardBindingInfoList = readExcel(filePath, value.getSheetIndex(), BankCardBindingInfoExcelDto.class);
                    List<BankCardBindingInfo> bankCardBindingInfos = new ArrayList<>();
                    for (BankCardBindingInfoExcelDto bankCardBindingInfoExcelDto : addBankCardBindingInfoList) {
                        BankCardBindingInfo bankCardBindingInfo = new BankCardBindingInfo();
                        BeanUtils.copyProperties(bankCardBindingInfoExcelDto, bankCardBindingInfo);
                        bankCardBindingInfos.add(bankCardBindingInfo);

                        if (bankCardBindingInfos.size() == 1000) {
                            bankCardBindingInfoDao.saveBatch(bankCardBindingInfos);
                            bankCardBindingInfos.clear();
                        }
                    }
                    if (!CollectionUtils.isEmpty(bankCardBindingInfos)) {
                        bankCardBindingInfoDao.saveBatch(bankCardBindingInfos);
                    }
                    break;
                case BANK_PUBLIC_PRIMITIVE:
                    List<BankPublicPrimitiveExcelDto> addBankPublicPrimitiveList = readExcel(filePath, value.getSheetIndex(), BankPublicPrimitiveExcelDto.class);
                    List<BankPublicPrimitive> bankPublicPrimitives = new ArrayList<>();

                    for (BankPublicPrimitiveExcelDto bankPublicPrimitiveExcelDto : addBankPublicPrimitiveList) {
                        if (StringUtils.isEmpty(bankPublicPrimitiveExcelDto.getMctNo())) {
                            continue;
                        }
                        BankPublicPrimitive bankPublicPrimitive = new BankPublicPrimitive();
                        BeanUtils.copyProperties(bankPublicPrimitiveExcelDto, bankPublicPrimitive);
                        BankPublicPrimitive byMctNo = bankPublicPrimitiveDao.getByMctNo(bankPublicPrimitiveExcelDto.getMctNo());
                        if (!Objects.isNull(byMctNo)) {
                            bankPublicPrimitive.setId(byMctNo.getId());
                        }
                        bankPublicPrimitives.add(bankPublicPrimitive);

                        if (bankPublicPrimitives.size() == 1000) {
                            bankPublicPrimitiveDao.saveOrUpdateBatch(bankPublicPrimitives);
                            bankPublicPrimitives.clear();
                        }
                    }

                    if (!CollectionUtils.isEmpty(bankPublicPrimitives)) {
                        bankPublicPrimitiveDao.saveBatch(bankPublicPrimitives);
                    }
                    break;
                case BANK_PUBLIC_TRADE_PRIMITIVE:
                    List<BankPublicTradePrimitiveExcelDto> addBankPublicTradePrimitiveList = readExcel(filePath, value.getSheetIndex(), BankPublicTradePrimitiveExcelDto.class);

                    List<BankPublicTradePrimitive> bankPublicTradePrimitives = new ArrayList<>();
                    for (BankPublicTradePrimitiveExcelDto bankPublicTradePrimitiveExcelDto : addBankPublicTradePrimitiveList) {
                        if (StringUtils.isEmpty(bankPublicTradePrimitiveExcelDto.getMctNo())) {
                            continue;
                        }
                        BankPublicTradePrimitive bankPublicTradePrimitive = new BankPublicTradePrimitive();

                        BeanUtils.copyProperties(bankPublicTradePrimitiveExcelDto, bankPublicTradePrimitive);

                        bankPublicTradePrimitives.add(bankPublicTradePrimitive);

                        if (bankPublicTradePrimitives.size() == 1000) {
                            bankPublicTradePrimitiveDao.saveBatch(bankPublicTradePrimitives);
                            bankPublicTradePrimitives.clear();
                        }
                    }
                    if (!CollectionUtils.isEmpty(bankPublicTradePrimitives)) {
                        bankPublicTradePrimitiveDao.saveBatch(bankPublicTradePrimitives);
                    }
                    break;
                default:
                    break;
            }

            log.info("【ManageTagInfoServiceImpl.getDataByFileTwo】end");
        }

//        List<BankPublicPrimitiveExcelDto> publicPrimitiveExcelDtos = readExcel(filePath, 0, BankPublicPrimitiveExcelDto.class);
//        publicPrimitiveExcelDtos.forEach(p->{
//            BankPublicPrimitive publicPrimitive = new BankPublicPrimitive();
//            //参数检查
//            BeanUtils.copyProperties(p,publicPrimitive);
//            publicPrimitive.setAccountStatus(0);
//            publicPrimitive.setAccountOpeningTime(LocalDateTime.now());
//            System.out.println(publicPrimitive);
//
//            bankPublicPrimitiveDao.save(publicPrimitive);
//
//        });
    }


    public void getDataByFile(String filePath, Integer type) {
        log.info("【ManageTagInfoServiceImpl.getDataByFile】start==>{},{}", filePath, type);
        for (BankFileTypeEnum value : BankFileTypeEnum.values()) {
            Class aClass = GetBankFileTypeObjectManage.GetBankFileTypeClass(value);
            if (Objects.isNull(aClass)) {
                continue;
            }
            if (!value.getType().equals(type)) {
                continue;
            }

            List list = readExcelData(filePath, type, value.getSheetIndex(), aClass);
            if (CollectionUtils.isEmpty(list)) {
                continue;
            }
            Object o = null;
            try {
                o = aClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("【ManageTagInfoServiceImpl.getDataByFile】 读取文件失败", e);
                throw new BaseException(ErrorCodeEnums.BANK_DATA_READ_IS_ERROR);
            }

            if (o instanceof BankCustomerInfo) {
                List<BankCustomerInfo> addCustomerInfoList = new ArrayList<>();
                List<BankCustomerInfo> editCustomerInfoList = new ArrayList<>();

                for (Object object : list) {
                    BankCustomerInfo bankCustomerInfo = (BankCustomerInfo) object;

                    BankCustomerInfo bankCustomerInfoByCstId = bankCustomerInfoDao.getBankCustomerInfoByCstId(bankCustomerInfo.getCstId());
                    if (Objects.isNull(bankCustomerInfoByCstId)) {
                        addCustomerInfoList.add(bankCustomerInfo);
                    } else {
                        bankCustomerInfo.setId(bankCustomerInfoByCstId.getId());
                        editCustomerInfoList.add(bankCustomerInfo);
                    }
                }
                if (!addCustomerInfoList.isEmpty()) {
                    bankCustomerInfoDao.saveBatch(addCustomerInfoList);
                }
                if (!editCustomerInfoList.isEmpty()) {
                    bankCustomerInfoDao.updateBatchById(editCustomerInfoList);
                }

            } else if (o instanceof BankPrivatePrimitive) {

                List<BankPrivatePrimitive> addBankPrivatePrimitives = new ArrayList<>();

                for (Object object : list) {
                    BankPrivatePrimitive bankPrivatePrimitive = (BankPrivatePrimitive) object;
                    addBankPrivatePrimitives.add(bankPrivatePrimitive);
                }
                bankPrivatePrimitiveDao.saveBatch(addBankPrivatePrimitives);
            } else if (o instanceof BankCardDataInfo) {
                List<BankCardDataInfo> addBankCardDataInfoList = new ArrayList<>();
                for (Object object : list) {
                    BankCardDataInfo bankCardDataInfo = (BankCardDataInfo) object;
                    addBankCardDataInfoList.add(bankCardDataInfo);
                }
                bankCardDataInfoDao.saveBatch(addBankCardDataInfoList);
            } else if (o instanceof BankProductDataInfo) {
                List<BankProductDataInfo> addBankProductDataInfoList = new ArrayList<>();
                for (Object object : list) {
                    BankProductDataInfo bankProductDataInfo = (BankProductDataInfo) object;
                    addBankProductDataInfoList.add(bankProductDataInfo);
                }
                bankProductDataInfoDao.saveBatch(addBankProductDataInfoList);

            } else if (o instanceof BankCustomerSignInfo) {
                List<BankCustomerSignInfo> addBankCustomerSignInfoList = new ArrayList<>();
                for (Object object : list) {
                    BankCustomerSignInfo bankCustomerSignInfo = (BankCustomerSignInfo) object;
                    addBankCustomerSignInfoList.add(bankCustomerSignInfo);
                }
                bankCustomerSignInfoDao.saveBatch(addBankCustomerSignInfoList);
            } else if (o instanceof BankCardBindingInfo) {
                List<BankCardBindingInfo> addBankCardBindingInfoList = new ArrayList<>();
                for (Object object : list) {
                    BankCardBindingInfo bankCardBindingInfo = (BankCardBindingInfo) object;
                    addBankCardBindingInfoList.add(bankCardBindingInfo);
                }
                bankCardBindingInfoDao.saveBatch(addBankCardBindingInfoList);
            } else if (o instanceof BankPublicPrimitive) {
                List<BankPublicPrimitive> addBankPublicPrimitiveList = new ArrayList<>();
                for (Object object : list) {
                    BankPublicPrimitive bankPublicPrimitive = (BankPublicPrimitive) object;
                    addBankPublicPrimitiveList.add(bankPublicPrimitive);
                }
                bankPublicPrimitiveDao.saveBatch(addBankPublicPrimitiveList);
            } else if (o instanceof BankPublicTradePrimitive) {
                List<BankPublicTradePrimitive> addBankPublicTradePrimitiveList = new ArrayList<>();
                for (Object object : list) {
                    BankPublicTradePrimitive bankPublicTradePrimitive = (BankPublicTradePrimitive) object;
                    addBankPublicTradePrimitiveList.add(bankPublicTradePrimitive);
                }
                bankPublicTradePrimitiveDao.saveBatch(addBankPublicTradePrimitiveList);
            }

        }
        log.info("【ManageTagInfoServiceImpl.getDataByFile】end");
    }

    public <E> List<E> readExcelData(String filePath, int type, int sheetIndex, Class<E> clazz) {


        List<E> datas = new ArrayList<>();
        // 定义输入流
        FileInputStream fis = null;
        List<ConditionsName> list = conditionsNameDao.findConditionsNameByTypeAndSheet(type, sheetIndex);
        if (CollectionUtils.isEmpty(list)) {
            return datas;
        }
        Map<String, String> maps = list.stream().filter(s -> !StringUtils.isEmpty(s.getConditionsValueKey())).collect(Collectors.toMap(s -> s.getConditionsValueKeyIndex() + "", ConditionsName::getConditionsValueKey));


        try {

            fis = new FileInputStream(filePath);
            Workbook readwb = Workbook.getWorkbook(fis);
            Sheet readsheet = readwb.getSheet(sheetIndex);
            long rsRows = readsheet.getRows();
            for (int i = 1; i < rsRows; i++) { // 获取指定单元格的对象引用
                jxl.Cell cell[] = readsheet.getRow(i);
                if (cell != null) {
                    if (cell.length < 1 || StringUtils.isEmpty(cell[0].getContents())) {
                        continue;
                    }
                    int j = 1;
                    E e1 = clazz.newInstance();
                    for (jxl.Cell c : cell) {

                        String s = maps.get(j + "");
                        if (!StringUtils.isEmpty(s) && !StringUtils.isEmpty(c.getContents())) {
                            String contents = c.getContents();
                            if (c.getType() == CellType.DATE) {
                                DateCell dc = (DateCell) c;
                                Date date = dc.getDate();
                                contents = cn.hutool.core.date.DateUtil.format(date, "yyyy-MM-dd hh:mm:ss");
                            }
                            setValue(e1, s, contents);
                        }

                        j++;
                    }
                    datas.add(e1);

                }
            }
        } catch (IOException | InstantiationException | IllegalAccessException | BiffException e) {
            log.error("【ManageTagInfoServiceImpl.readExcelData】读取Excel错误", e);
            throw new BaseException(ErrorCodeEnums.BANK_EXCEL_READ_IS_ERROR);
        }

        return datas;
    }

    /**
     * @param filePath   Excel文件路径
     * @param sheetIndex 对应的表单，从0开始，0代表第一个表单
     * @param clazz      对应封装的数据实例对象
     * @return 返回数据集合
     */
    public static <E> List<E> readExcel(String filePath, int sheetIndex, Class<E> clazz) {
        // 定义输入流
        FileInputStream fis = null;
        List<E> datas = null;

        try {
            // 创建输入流对象
            fis = new FileInputStream(filePath);
            // 创建一个easypoi使用的配置类
            ImportParams params = new ImportParams();
            // 设置表格坐标
            params.setStartSheetIndex(sheetIndex);
            // 校验Excel文件，去掉空行
            params.setNeedVerify(true);
            // 读取数据
            datas = ExcelImportUtil.importExcel(fis, clazz, params);
        } catch (Exception e) {
            log.error("【ManageTagInfoServiceImpl.readExcel】读取excel文件失败", e);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                log.error("【ManageTagInfoServiceImpl.readExcel】读取excel文件失败", e);
            }
        }

        return datas;
    }


    /**
     * 获取每个单元格的值
     *
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }

        // 判断数据的类型
        switch (cell.getCellType()) {
            case NUMERIC: // 数字
                cellValue = stringDateProcess(cell);
                break;
            case STRING: // 字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case BOOLEAN: // Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());

                break;
//            case CellType.FORMULA: // 公式
//                if (formulaEvaluator != null) {
//                    CellValue evaluate = formulaEvaluator.evaluate(cell);
//                    cellValue = evaluate.formatAsString();
//                }else{
//                    try {
//                        cellValue = String.valueOf(cell.getNumericCellValue());
//                    } catch (IllegalStateException e) {
//                        cellValue = String.valueOf(cell.getRichStringCellValue());
//                    }
//                }
//                if (cellValue == null || "".equals(cellValue.trim()) || "\"\"".equals(cellValue.trim())){
//                    return "";
//                }
//                //解决读取一个数字时会带小数点问题
//                NumberFormat nf = NumberFormat.getInstance();
//                cellValue = nf.format(Double.valueOf(cellValue));
//                if (cellValue.contains(",")) {
//                    cellValue  = cellValue.replace(",", "");
//                }
//                break;
            case BLANK: // 空值
                cellValue = "";
                break;
            case ERROR: // 故障
                cellValue = "";
                break;
            default:
                cellValue = "";
                break;
        }
        return cellValue;
    }

    public static String stringDateProcess(Cell cell) {
        String result = new String();
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            double cur = cell.getNumericCellValue();

            String dataFormat = cell.getCellStyle().getDataFormatString();

            //处理日期格式问题
            if ("m/d/yy h:mm".equals(dataFormat)) {
                Date d = DateUtil.getJavaDate(cur);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return f.format(d);
            }
            if ("m\"月\"d\"日\";@".equals(dataFormat)) {
                Date d = DateUtil.getJavaDate(cur);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                return f.format(d);
            } else if ("m/d/yy".equals(dataFormat)
                    || "yyyy\\-mm\\-dd".equals(dataFormat)
                    || "yyyy/m/d;@".equals(dataFormat)
                    || "yyyy\"年\"m\"月\"d\"日\";@".equals(dataFormat)) {
                Date d = DateUtil.getJavaDate(cur);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                return f.format(d);
            }
            //处理时间格式问题
            else if ("yyyy/m/d\\ h:mm;@".equals(dataFormat)) {
                Date d = DateUtil.getJavaDate(cur);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return f.format(d);
            } else if ("General".equals(dataFormat)) {
                long longVal = Math.round(cur);
                Object inputValue = null;
                if (Double.parseDouble(longVal + ".0") == cur)
                    inputValue = longVal;
                else
                    inputValue = cur;
                return String.valueOf(inputValue);
            }
            return String.valueOf(cur);

            // 处理日期格式、时间格式
//            SimpleDateFormat sdf = null;
//            short builtinFormat = HSSFDataFormat.getBuiltinFormat("h:mm");
//            short builtinFormat1 = HSSFDataFormat.getBuiltinFormat("d-mmm-yy");
//            short dataFormat = cell.getCellStyle().getDataFormat();
//            if ( dataFormat== builtinFormat) {
//                sdf = new SimpleDateFormat("HH:mm");
//            }else if (dataFormat==builtinFormat1){
//                sdf = new SimpleDateFormat("yyyy-MM-dd");
//            }
//            else {// 日期
//                sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//            }
//
//
//            Date date = cell.getDateCellValue();
//            result = sdf.format(date);


        } else if (cell.getCellStyle().getDataFormat() == 58) {
            // 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//            Date date = org.apache.poi.ss.usermodel.DateUtil
//                    .getJavaDate(cell.getNumericCellValue());
            Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
            result = sdf.format(date);
        } else {
            //解决读取一个数字时会带小数点问题
            NumberFormat nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(20);
            result = nf.format(cell.getNumericCellValue());
            if (result.contains(",")) {
                result = result.replace(",", "");
            }
        }

        return result;
    }


    public static void setValue(Object obj, String fieldName, String value) {

        // 创建一个对象
//        PrivatePrimitive myObject = new PrivatePrimitive();

        // 获取字段的Class对象
//        Class<?> clazz = myObject.getClass();
        Class<?> clazz = obj.getClass();
        // 通过字段名获取Field对象
        Field field = null;
        try {
            field = clazz.getDeclaredField(fieldName);

            // 如果字段是私有的，需要设置setAccessible(true)来绕过访问权限检查
            field.setAccessible(true);

            if (field.getType().equals(Integer.class)) {
                // 如果属性是int类型，而值是String类型，尝试转换

                Integer intValue = Integer.parseInt(value);
                field.set(obj, intValue);
            } else if (field.getType().equals(Long.class)) {
                Long intValue = Long.parseLong(value);
                field.set(obj, intValue);
            } else if (field.getType().equals(Double.class)) {
                Double doubleValue = Double.parseDouble(value);
                field.set(obj, doubleValue);
            } else if (field.getType().equals(BigDecimal.class)) {
                BigDecimal bigDecimalValue = new BigDecimal(value);
                field.set(obj, bigDecimalValue);
            } else if (field.getType().equals(LocalDateTime.class)) {

                DateTime parse = cn.hutool.core.date.DateUtil.parse(value);
                LocalDateTime localDate = LocalDateTimeUtil.of(parse);
                field.set(obj, localDate);
            } else if (field.getType().equals(LocalDate.class)) {
                LocalDate localDate = DateTimeUtil.parseYYYYMMDD(getYYYYMMDDDate(value));
                field.set(obj, localDate);
            } else {
                // 直接设置值，确保类型匹配
                field.set(obj, value);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("【ManageTagInfoServiceImpl.setValue赋值错误】", e);
            throw new BaseException(ErrorCodeEnums.BANK_FILE_SET_VALUE_ERROR);
        }


        // 给字段赋值
//        try {
//            field.set(obj, value);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
    }

    public static String getYYYYMMDDDate(String date) {

//String result = date;

        String dateType = date.trim();

        dateType = dateType.replace("/", "").replace(".", "").replace("-", "").replace("年", "").replace("月", "").replace("日", "");

        return QxAndJhUtil.get8VaildDate(dateType);

    }

    @Override
    public void asyncUpdateVipTag(Long tagId, List<ConditionsInfo> byTagId, LocalDateTime updateTime, Integer tagHisId) {
        List<TagProducer> tagProducers = new ArrayList<>();
        for (int s = 0; s < byTagId.size(); s++) {
            ConditionsInfo conditionsInfo = byTagId.get(s);
            ConditionsName conditionsName = conditionsNameDao.getById(conditionsInfo.getConditionsId());
            Integer classId = conditionsName.getClassId();
            ConditionsClassEnum conditionsClassEnum = ConditionsClassEnum.getByValue(classId);
            if (Objects.isNull(conditionsClassEnum)) {
                return;
            }

            ParentDateTypeConstant parentDateTypeConstant = getParentDateTypeConstant(conditionsName.getConditionsDataTypeId());
            if (Objects.isNull(parentDateTypeConstant)) {
                return;
            }
            String columnName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, conditionsName.getConditionsValueKey());
            Long conditionsExpressionId = conditionsInfo.getConditionsExpressionId();
            //匹配对应表达式
            if (Objects.nonNull(conditionsExpressionId)) {
                int i = conditionsExpressionId.intValue();
                if (i == ExpressionTypeEnum.TYPE_BETWEEN.getValue()) {
                    if (!parentDateTypeConstant.between()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    TagProducer tagProducer2 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr(">=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer2.setColumnName(columnName);
                    tagProducer2.setCompareStr("<=");
                    tagProducer2.setValue(conditionsInfo.getData2());
                    tagProducer2.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);
                    tagProducers.add(tagProducer2);
                } else if (i == ExpressionTypeEnum.TYPE_NOT_BETWEEN.getValue()) {
                    if (!parentDateTypeConstant.notBetween()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setOrFlag(BasicConstant.INT_1);
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    List<TagProducerForOR> orList = new ArrayList<>();
                    TagProducerForOR forOR1 = new TagProducerForOR();
                    TagProducerForOR forOR2 = new TagProducerForOR();
                    forOR1.setCompareStr("<=");
                    forOR1.setValue(conditionsInfo.getData1());
                    forOR2.setCompareStr(">=");
                    forOR2.setValue(conditionsInfo.getData2());
                    orList.add(forOR1);
                    orList.add(forOR2);
                    tagProducer1.setOrList(orList);
                    tagProducers.add(tagProducer1);
                } else if (i == ExpressionTypeEnum.TYPE_EQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.equalTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());

                    if (conditionsInfo.getData1().contains(";")) {
                        tagProducer1.setCompareStr(" IN ");
                        String data = conditionsInfo.getData1().replaceAll(";", "','");
                        tagProducer1.setValue("('" + data + "')");
                    } else {
                        tagProducer1.setCompareStr("=");
                        tagProducer1.setValue(conditionsInfo.getData1());
                    }


                    tagProducers.add(tagProducer1);

                } else if (i == ExpressionTypeEnum.TYPE_NOTEQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.notEqualTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr("!=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);
                } else if (i == ExpressionTypeEnum.TYPE_GREATER_THAN.getValue()) {
                    if (!parentDateTypeConstant.greaterThan()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr(">");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);
                } else if (i == ExpressionTypeEnum.TYPE_LESS_THAN.getValue()) {
                    if (!parentDateTypeConstant.lessThan()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr("<");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);

                } else if (i == ExpressionTypeEnum.TYPE_GREATER_THAN_EQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.greaterThanEqualTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr(">=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);

                } else if (i == ExpressionTypeEnum.TYPE_LESS_THAN_EQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.lessThanEqualTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr("<=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);
                } else if (i == ExpressionTypeEnum.TYPE_LIKE.getValue()) {
                    if (!parentDateTypeConstant.like()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr(" LIKE ");
                    tagProducer1.setValue("%" + conditionsInfo.getData1() + "%");
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducers.add(tagProducer1);
                }
            }
        }
        forPrivateTagProducer(tagProducers, tagId, updateTime, tagHisId);
    }

    @Override
    public void asyncUpdateMctTag(Long tagId, List<ConditionsInfo> byTagId, LocalDateTime updateTime, Integer tagHisId) {
        List<TagProducer> tagProducers = new ArrayList<>();
        List<TagProducer> tagPrivateProducers = new ArrayList<>();
        boolean mctInduStryFlag = false;
        for (int s = 0; s < byTagId.size(); s++) {
            ConditionsInfo conditionsInfo = byTagId.get(s);
            ConditionsName conditionsName = conditionsNameDao.getById(conditionsInfo.getConditionsId());
            Integer classId = conditionsName.getClassId();
            ConditionsClassEnum conditionsClassEnum = ConditionsClassEnum.getByValue(classId);
            if (Objects.isNull(conditionsClassEnum)) {
                return;
            }
            //是否是对私会员相关表
            Boolean joinPrivateFlag = ConditionsClassEnum.forPrivateEnums().contains(conditionsClassEnum.getValue());

            ParentDateTypeConstant parentDateTypeConstant = getParentDateTypeConstant(conditionsName.getConditionsDataTypeId());
            if (Objects.isNull(parentDateTypeConstant)) {
                return;
            }

            String columnName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, conditionsName.getConditionsValueKey());
            Long conditionsExpressionId = conditionsInfo.getConditionsExpressionId();
            //匹配对应表达式
            if (Objects.nonNull(conditionsExpressionId)) {
                int i = conditionsExpressionId.intValue();
                if (i == ExpressionTypeEnum.TYPE_BETWEEN.getValue()) {
                    if (!parentDateTypeConstant.between()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    TagProducer tagProducer2 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer1.setCompareStr(">=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    tagProducer2.setColumnName(columnName);
                    tagProducer2.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer2.setCompareStr("<=");
                    tagProducer2.setValue(conditionsInfo.getData2());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                        tagPrivateProducers.add(tagProducer2);
                    } else {
                        tagProducers.add(tagProducer1);
                        tagProducers.add(tagProducer2);
                    }
                } else if (i == ExpressionTypeEnum.TYPE_NOT_BETWEEN.getValue()) {
                    if (!parentDateTypeConstant.notBetween()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setOrFlag(BasicConstant.INT_1);
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    List<TagProducerForOR> orList = new ArrayList<>();
                    TagProducerForOR forOR1 = new TagProducerForOR();
                    TagProducerForOR forOR2 = new TagProducerForOR();
                    forOR1.setCompareStr("<=");
                    forOR1.setValue(conditionsInfo.getData1());
                    forOR2.setCompareStr(">=");
                    forOR2.setValue(conditionsInfo.getData2());
                    orList.add(forOR1);
                    orList.add(forOR2);
                    tagProducer1.setOrList(orList);
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }
                } else if (i == ExpressionTypeEnum.TYPE_EQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.equalTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    if ("mct_industry".equals(columnName)) {
                        //有所属行业条件
                        tagProducer1.setConditionsClassEnumValue(ConditionsClassEnum.BANK_PUBLIC_INDUSTRY.getValue());
                    } else {
                        tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    }
                    if (conditionsInfo.getData1().contains(";")) {
                        tagProducer1.setCompareStr(" IN ");
                        String data = conditionsInfo.getData1().replaceAll(";", "','");
                        tagProducer1.setValue("('" + data + "')");
                    } else {
                        tagProducer1.setCompareStr("=");
                        tagProducer1.setValue(conditionsInfo.getData1());
                    }
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }
                } else if (i == ExpressionTypeEnum.TYPE_NOTEQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.notEqualTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer1.setCompareStr("!=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }
                } else if (i == ExpressionTypeEnum.TYPE_GREATER_THAN.getValue()) {
                    if (!parentDateTypeConstant.greaterThan()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer1.setCompareStr(">");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }
                } else if (i == ExpressionTypeEnum.TYPE_LESS_THAN.getValue()) {
                    if (!parentDateTypeConstant.lessThan()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer1.setCompareStr("<");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }

                } else if (i == ExpressionTypeEnum.TYPE_GREATER_THAN_EQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.greaterThanEqualTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer1.setCompareStr(">=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }

                } else if (i == ExpressionTypeEnum.TYPE_LESS_THAN_EQUAL_TO.getValue()) {
                    if (!parentDateTypeConstant.lessThanEqualTo()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    tagProducer1.setCompareStr("<=");
                    tagProducer1.setValue(conditionsInfo.getData1());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }
                } else if (i == ExpressionTypeEnum.TYPE_LIKE.getValue()) {
                    if (!parentDateTypeConstant.like()) {
                        return;
                    }
                    TagProducer tagProducer1 = new TagProducer();
                    tagProducer1.setColumnName(columnName);
                    tagProducer1.setCompareStr(" LIKE ");
                    tagProducer1.setValue("%" + conditionsInfo.getData1() + "%");
                    tagProducer1.setConditionsClassEnumValue(conditionsClassEnum.getValue());
                    if (joinPrivateFlag) {
                        tagPrivateProducers.add(tagProducer1);
                    } else {
                        tagProducers.add(tagProducer1);
                    }
                }
            }
        }
        forPublicTagProducer(tagProducers, tagPrivateProducers, tagId, updateTime, tagHisId);
    }


    @Override
    public void forPrivateTagProducer(List<TagProducer> tags, Long tagId, LocalDateTime updateTime, Integer tagHisId) {
        //根据条件字段所在表分组
        Map<Integer, List<TagProducer>> tagsMap = tags.stream().collect(Collectors.groupingBy(TagProducer::getConditionsClassEnumValue));
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String format = "2" + decimalFormat.format(tagId);
        StringBuilder builder = new StringBuilder("SELECT CONCAT(" + format + ",vip_id)," + tagId + ",vip_id,'" + DateTimeUtil.formatYYYY_MM_DD_HH_MM_SS(LocalDateTime.now()) + "' FROM tbl_app_coupon_vip");
        //是否有主表查询条件
        List<TagProducer> tagProducerMain = tagsMap.get(ConditionsClassEnum.BANK_CUSTOMER_INFO.getValue());
        boolean tbMainFlag = !CollectionUtils.isEmpty(tagProducerMain);
        if (tbMainFlag) {
            //主表不参与for循环构造连表sql
            tagsMap.remove(ConditionsClassEnum.BANK_CUSTOMER_INFO.getValue());
        }
        if (!CollectionUtils.isEmpty(tagsMap)) {
            List<Integer> keys = new ArrayList<>(tagsMap.keySet());
            //连表sql构造
            for (int i = 0; i < keys.size(); i++) {
                Integer conditionsClassEnumValue = keys.get(i);
                //表名
                String tableName = ConditionsClassEnum.getTableNameByValue(conditionsClassEnumValue);
                List<TagProducer> tbProducers = tagsMap.get(conditionsClassEnumValue);
                builder.append(" INNER JOIN ( SELECT cst_id AS cst").append(i);
                StringBuilder having = new StringBuilder(" HAVING ");
                boolean havingFlag = false;
                if (ConditionsClassEnum.needSumByAgent(conditionsClassEnumValue)) {
                    List<TagProducer> removeProducers = new ArrayList<>();
                    List<String> sumColumnName = new ArrayList<>();
                    for (int j = 0; j < tbProducers.size(); j++) {
                        TagProducer producer = tbProducers.get(j);
                        if (sumColumnName.contains(producer.getColumnName())) {
                            removeProducers.add(producer);
                            having.append(" AND ").append(producer.getColumnName()).append(producer.getCompareStr()).append(producer.getValue());
                            continue;
                        }
                        if (producer.getColumnName().contains("amount")) {
                            builder.append(",SUM(").append(producer.getColumnName()).append(") AS ").append(producer.getColumnName());
                            if (j != 0) {
                                having.append(" AND");
                            }
                            having.append(" ").append(producer.getColumnName()).append(producer.getCompareStr()).append(producer.getValue());
                            removeProducers.add(producer);
                            sumColumnName.add(producer.getColumnName());
                            havingFlag = true;
                        }
                    }
                    tbProducers.removeAll(removeProducers);
                }
                String tbAlias = "t" + conditionsClassEnumValue;
                builder.append(" FROM ").append(tableName).append(" ").append(tbAlias);
                if (conditionsClassEnumValue.equals(ConditionsClassEnum.BANK_CARD_BINDING_INFO.getValue())) {
                    builder.append(" INNER JOIN tbl_bank_card_data_info b ON ").append(tbAlias).append(".bank_card_number = b.bank_card_number");
                }
                for (int j = 0; j < tbProducers.size(); j++) {
                    TagProducer tbProducer = tbProducers.get(j);
                    if (j != 0) {
                        builder.append(" AND ");
                    } else {
                        builder.append(" WHERE ");
                    }
                    if (tbProducer.getOrFlag() == 1) {
                        builder.append("(");
                        for (int k = 0; k < tbProducer.getOrList().size(); k++) {
                            TagProducerForOR forOR = tbProducer.getOrList().get(k);
                            if ((k != 0)) {
                                builder.append(" OR ");
                            }
                            builder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(forOR.getCompareStr()).append("'").append(forOR.getValue()).append("'");
                        }
                        builder.append(")");
                        continue;
                    }
                    if (tbProducer.getCompareStr().contains("IN")) {
                        builder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append(tbProducer.getValue());
                    } else {
                        builder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append("'").append(tbProducer.getValue()).append("'");
                    }
                }
                if (havingFlag) {
                    builder.append(" GROUP BY cst_id").append(having);
                }
                builder.append(") t").append(i).append(" ON cst").append(i).append(" = ").append("vip_cst_id");
            }
        }
        if (tbMainFlag) {
            builder.append(" WHERE ");
            for (int s = 0; s < tagProducerMain.size(); s++) {
                TagProducer mainTagProducer = tagProducerMain.get(s);
                if (s != 0) {
                    builder.append(" AND ");
                }
                if (mainTagProducer.getCompareStr().contains("IN")) {
                    builder.append(mainTagProducer.getColumnName()).append(mainTagProducer.getCompareStr()).append(mainTagProducer.getValue());
                } else {
                    builder.append(mainTagProducer.getColumnName()).append(mainTagProducer.getCompareStr()).append("'").append(mainTagProducer.getValue()).append("'");
                }
            }
        }
        builder.append(" GROUP BY vip_id");
        String sql = builder.toString();
        log.info("forPrivateTagProducer 拼接sql: " + sql);

        LambdaQueryWrapper<VipBindTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VipBindTag::getTagId, tagId);
        List<VipBindTag> listDeleteVip = vipBindTagDao.list(queryWrapper);
        Set<Long> deleteVipMap = listDeleteVip.stream().map(VipBindTag::getVipId) .collect(Collectors.toSet());

        vipBindTagDao.deleteBytagId(tagId);
        int tagVipNum = vipBindTagDao.addVipBindTag(sql);
        TagInfo tagInfo = new TagInfo();
        tagInfo.setId(tagId);
        tagInfo.setTagPeopleNumber(tagVipNum);
        if (Objects.nonNull(updateTime)) {
            tagInfo.setUpdateTime(updateTime);
        }
        tagInfoDao.updateById(tagInfo);
        syncToMarket(tagInfo);
        updateTagHis(tagInfo, tagHisId, VersionStatusEnum.SUCCESS.getCode(),deleteVipMap);
    }

    @Override
    public void forPublicTagProducer(List<TagProducer> tags, List<TagProducer> tagPrivateProducers, Long tagId, LocalDateTime updateTime, Integer tagHisId) {
        //根据条件字段所在表分组
        Map<Integer, List<TagProducer>> tagsMap = tags.stream().collect(Collectors.groupingBy(TagProducer::getConditionsClassEnumValue));
        if (CollectionUtils.isEmpty(tagsMap) && CollectionUtils.isEmpty(tagPrivateProducers)) {
            return;
        }
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String format = GradeTypeEnum.TYPE_PUBLIC.getValue() + decimalFormat.format(tagId);
        List<Integer> keys = new ArrayList<>(tagsMap.keySet());
        StringBuilder builder = new StringBuilder("SELECT CONCAT(" + format + ",t0.mct_no)," + tagId + ",t0.mct_no,'" + DateTimeUtil.formatYYYY_MM_DD_HH_MM_SS(LocalDateTime.now()) + "' FROM ");
        //连表sql构造
        for (int i = 0; i < keys.size(); i++) {
            Integer conditionsClassEnumValue = keys.get(i);
            //表名
            String tableName = ConditionsClassEnum.getTableNameByValue(conditionsClassEnumValue);
            if (i == 0) {
                if (conditionsClassEnumValue.equals(ConditionsClassEnum.BANK_PUBLIC_PRIMITIVE.getValue())) {
                    builder.append("( SELECT mct_no,mct_id_number FROM " + tableName);
                } else if (conditionsClassEnumValue.equals(ConditionsClassEnum.BANK_PUBLIC_INDUSTRY.getValue())) {
                    builder.append("( WITH RECURSIVE split_mct_industry AS ( SELECT mct_no, SUBSTRING_INDEX(mct_industry, ',', 1) AS mct_industry, SUBSTRING( mct_industry, LENGTH( SUBSTRING_INDEX(mct_industry, ',', 1) ) + 2 )AS rest FROM tbl_bank_public_primitive UNION ALL SELECT mct_no, SUBSTRING_INDEX(rest, ',', 1) AS mct_industry, SUBSTRING( rest, LENGTH( SUBSTRING_INDEX(rest, ',', 1) ) + 2 )AS rest FROM split_mct_industry WHERE rest != '' ) SELECT mct_no, mct_industry FROM split_mct_industry");
                } else {
                    builder.append("( SELECT mct_no FROM " + tableName);
                }
            } else {
                if (conditionsClassEnumValue.equals(ConditionsClassEnum.BANK_PUBLIC_PRIMITIVE.getValue())) {
                    builder.append(" INNER JOIN ( SELECT mct_no,mct_id_number FROM " + tableName);
                } else if (conditionsClassEnumValue.equals(ConditionsClassEnum.BANK_PUBLIC_INDUSTRY.getValue())) {
                    builder.append(" INNER JOIN ( WITH RECURSIVE split_mct_industry AS ( SELECT mct_no, SUBSTRING_INDEX(mct_industry, ',', 1) AS mct_industry, SUBSTRING( mct_industry, LENGTH( SUBSTRING_INDEX(mct_industry, ',', 1) ) + 2 )AS rest FROM tbl_bank_public_primitive UNION ALL SELECT mct_no, SUBSTRING_INDEX(rest, ',', 1) AS mct_industry, SUBSTRING( rest, LENGTH( SUBSTRING_INDEX(rest, ',', 1) ) + 2 )AS rest FROM split_mct_industry WHERE rest != '' ) SELECT mct_no, mct_industry FROM split_mct_industry");
                } else {
                    builder.append(" INNER JOIN ( SELECT mct_no FROM " + tableName);
                }
            }
            builder.append(" WHERE ");
            List<TagProducer> tbProducers = tagsMap.get(conditionsClassEnumValue);
            for (int j = 0; j < tbProducers.size(); j++) {
                TagProducer tbProducer = tbProducers.get(j);
                if (j != 0) {
                    builder.append(" AND ");
                }
                if (tbProducer.getOrFlag() == 1) {
                    builder.append("(");
                    for (int k = 0; k < tbProducer.getOrList().size(); k++) {
                        TagProducerForOR forOR = tbProducer.getOrList().get(k);
                        if ((k != 0)) {
                            builder.append(" OR ");
                        }
                        builder.append(tbProducer.getColumnName() + forOR.getCompareStr() + "'" + forOR.getValue() + "'");
                    }
                    builder.append(")");
                    continue;
                }
                if (tbProducer.getCompareStr().contains("IN")) {
                    builder.append(tbProducer.getColumnName() + tbProducer.getCompareStr() + tbProducer.getValue());
                } else {
                    builder.append(tbProducer.getColumnName() + tbProducer.getCompareStr() + "'" + tbProducer.getValue() + "'");
                }

            }
            builder.append(") t" + i);
            if (i > 0) {
                builder.append(" ON t" + i + ".mct_no = t" + (i - 1) + ".mct_no");
            }
        }
        if (tagPrivateProducers.size() > 0) {
            String sql = forPublicJoinPrivateTagProducer(tagPrivateProducers);
            if (!keys.contains(ConditionsClassEnum.BANK_PUBLIC_PRIMITIVE.getValue())) {
                if (CollectionUtils.isEmpty(tagsMap)) {
                    builder.append(ConditionsClassEnum.BANK_PUBLIC_PRIMITIVE.getTableName()).append(" t0");
                } else {
                    builder.append(" INNER JOIN ").append(ConditionsClassEnum.BANK_PUBLIC_PRIMITIVE.getTableName()).append(" tm").append(" ON t0.mct_no = tm.mct_no");
                }
            }
            builder.append(" INNER JOIN ").append(sql).append(" tp").append(" ON mct_id_number = vip_id_card_no");
        }
        builder.append(" GROUP BY t0.mct_no");
        String sql = builder.toString();
        log.info("forPublicTagProducer 拼接sql: " + sql);

        LambdaQueryWrapper<VipBindTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VipBindTag::getTagId, tagId);
        List<VipBindTag> listDeleteVip = vipBindTagDao.list(queryWrapper);
        Set<Long> deleteVipMap = listDeleteVip.stream().map(VipBindTag::getVipId) .collect(Collectors.toSet());

        vipBindTagDao.deleteBytagId(tagId);
        int tagVipNum = vipBindTagDao.addMctBindTag(sql);

        //更新vipid
        updateMctVipId(tagId);

        TagInfo tagInfo = new TagInfo();
        tagInfo.setId(tagId);
        tagInfo.setTagPeopleNumber(tagVipNum);
        if (Objects.nonNull(updateTime)) {
            //定时任务更新标签时，重置该值
            tagInfo.setUpdateTime(updateTime);
        }
        tagInfoDao.updateById(tagInfo);

        //标签同步到营销平台
        syncToMarket(tagInfo);

        updateTagHis(tagInfo, tagHisId, VersionStatusEnum.SUCCESS.getCode(),deleteVipMap);
    }


    public void updateMctVipId(Long tagId) {
        LambdaQueryWrapper<VipBindTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VipBindTag::getTagId, tagId);
        List<VipBindTag> listBind = vipBindTagDao.list(queryWrapper);
        LambdaQueryWrapper<VipBindMerchant> q = new LambdaQueryWrapper<>();
        q.in(VipBindMerchant::getMctNo, listBind.stream()
                .map(VipBindTag::getMctNo)
                .collect(Collectors.toList()));
        List<VipBindMerchant> listVip = vipBindMerchantDao.list(q);
        Map<Long, Long> mctNoToVipIdMap = listVip.stream().collect(Collectors.toMap(VipBindMerchant::getMctNo, VipBindMerchant::getVipId));
        List<VipBindTag> toUpdateList = new ArrayList<>();
        for (VipBindTag bindTag : listBind) {
            Long mctNoLong = Long.valueOf(bindTag.getMctNo());
            Long vipId = mctNoToVipIdMap.get(mctNoLong);
            if (vipId != null && !vipId.equals(bindTag.getVipId())) {
                VipBindTag updateEntity = new VipBindTag();
                updateEntity.setId(bindTag.getId());
                updateEntity.setVipId(vipId);
                updateEntity.setTagId(bindTag.getTagId());
                updateEntity.setMctNo(bindTag.getMctNo());
                updateEntity.setAddTime(bindTag.getAddTime());
                toUpdateList.add(updateEntity);
            }
        }
        if (!toUpdateList.isEmpty()) {
            vipBindTagDao.updateBatchById(toUpdateList);
        }
    }

    @Override
    @RattingTask(taskEnum = TaskEnum.TAG_BIND_BACK_UP)
    public BaseResult backUp() {
        try {
            LocalDate todate = LocalDate.now();
            //每日备份，备份保留十日
            LocalDate removeDate = todate.minusDays(10);
            Integer removeDateInt = Integer.valueOf(DateTimeUtil.formatYYYYMMDD(todate));
            vipBindTagBackUpDao.deleteLtDate(removeDateInt);
            Integer todateInt = Integer.valueOf(DateTimeUtil.formatYYYYMMDD(todate));
            if (Objects.isNull(vipBindTagBackUpDao.queryByDateLimitOne(todateInt))) {
                vipBindTagBackUpDao.backUp(todateInt);
            } else {
                log.info("ManageTagInfoService backUp 标签日期{}已备份", todateInt);
            }
        } catch (Exception e) {
            log.error("ManageTagInfoService backUp 标签命中商户信息备份失败-----------{}" + e.getLocalizedMessage());
            throw e;
        }
        return BaseResult.success(true);
    }

    @Override
    public String forPublicJoinPrivateTagProducer(List<TagProducer> tags) {
        //根据条件字段所在表分组
        Map<Integer, List<TagProducer>> tagsMap = tags.stream().collect(Collectors.groupingBy(TagProducer::getConditionsClassEnumValue));
        //主语句
        StringBuilder builder = new StringBuilder("( SELECT tm.vip_id_card_no FROM tbl_app_coupon_vip tm ");
        //是否有主表查询条件
        List<TagProducer> tagProducerMain = tagsMap.get(ConditionsClassEnum.BANK_CUSTOMER_INFO.getValue());
        boolean tbMainFlag = !CollectionUtils.isEmpty(tagProducerMain);
        List<String> whereList = new ArrayList<>();
        if (tbMainFlag) {
            //主表不参与for循环构造连表sql
            tagsMap.remove(ConditionsClassEnum.BANK_CUSTOMER_INFO.getValue());
            for (int j = 0; j < tagProducerMain.size(); j++) {
                TagProducer tbProducer = tagProducerMain.get(j);
                StringBuilder whereBuilder = new StringBuilder();
                if (tbProducer.getOrFlag() == 1) {
                    whereBuilder.append("(");
                    for (int k = 0; k < tbProducer.getOrList().size(); k++) {
                        TagProducerForOR forOR = tbProducer.getOrList().get(k);
                        if ((k != 0)) {
                            whereBuilder.append(" OR ");
                        }
                        whereBuilder.append("tm").append(".").append(tbProducer.getColumnName()).append(forOR.getCompareStr()).append("'").append(forOR.getValue()).append("'");
                    }
                    whereBuilder.append(")");
                } else {
                    if (tbProducer.getCompareStr().contains("IN")) {
                        whereBuilder.append("tm").append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append(tbProducer.getValue());
                    } else {
                        whereBuilder.append("tm").append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append("'").append(tbProducer.getValue()).append("'");
                    }
                }
                whereList.add(String.valueOf(whereBuilder));
            }
        }

        //条件语句集合
        if (!CollectionUtils.isEmpty(tagsMap)) {
            List<Integer> keys = new ArrayList<>(tagsMap.keySet());
            //连表sql构造
            for (int i = 0; i < keys.size(); i++) {
                Integer conditionsClassEnumValue = keys.get(i);
                //表名
                String tableName = ConditionsClassEnum.getTableNameByValue(conditionsClassEnumValue);
                //表别名
                String tbAlias = "t" + conditionsClassEnumValue;
                //表连接语句
                if (conditionsClassEnumValue.equals(ConditionsClassEnum.BANK_CARD_BINDING_INFO.getValue())) {
                    String tbAlias2 = "t" + ConditionsClassEnum.BANK_CARD_DATA_INFO.getValue();
                    if (keys.contains(ConditionsClassEnum.BANK_CARD_DATA_INFO.getValue())) {
                        builder.append(" INNER JOIN ").append(tableName).append(" ").append(tbAlias).append(" ON ").append(tbAlias2).append(".bank_card_number = ").append(tbAlias).append(".bank_card_number ");
                    } else {
                        builder.append(" INNER JOIN ").append(ConditionsClassEnum.BANK_CARD_DATA_INFO.getTableName()).append(" ").append(tbAlias2).append(" ON ").append(tbAlias2).append(".cst_id = ").append("tm.vip_cst_id ");
                        builder.append(" INNER JOIN ").append(tableName).append(" ").append(tbAlias).append(" ON ").append(tbAlias2).append(".bank_card_number = ").append(tbAlias).append(".bank_card_number ");
                    }
                } else if (ConditionsClassEnum.needSumByAgent(conditionsClassEnumValue)) {
                    builder.append(" INNER JOIN ( SELECT cst_id");
                    List<TagProducer> tbProducers = tagsMap.get(conditionsClassEnumValue);
                    List<String> processedColumn = new ArrayList<>();
                    for (int j = 0; j < tbProducers.size(); j++) {
                        TagProducer tbProducer = tbProducers.get(j);
                        StringBuilder whereBuilder = new StringBuilder();
                        if ("cst_id".equals(tbProducer.getColumnName()) || processedColumn.contains(tbProducer.getColumnName())) {

                        } else if (tbProducer.getColumnName().contains("amount")) {
                            builder.append(",SUM(").append(tbProducer.getColumnName()).append(") AS ").append(tbProducer.getColumnName());
                        } else {
                            builder.append(",").append(tbProducer.getColumnName());
                        }
                        processedColumn.add(tbProducer.getColumnName());
                        if (tbProducer.getOrFlag() == 1) {
                            whereBuilder.append("(");
                            for (int k = 0; k < tbProducer.getOrList().size(); k++) {
                                TagProducerForOR forOR = tbProducer.getOrList().get(k);
                                if ((k != 0)) {
                                    whereBuilder.append(" OR ");
                                }
                                whereBuilder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(forOR.getCompareStr()).append("'").append(forOR.getValue()).append("'");
                            }
                            whereBuilder.append(")");
                        } else {
                            if (tbProducer.getCompareStr().contains("IN")) {
                                whereBuilder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append(tbProducer.getValue());
                            } else {
                                whereBuilder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append("'").append(tbProducer.getValue()).append("'");
                            }
                        }
                        whereList.add(String.valueOf(whereBuilder));
                    }
                    builder.append(" FROM ").append(tableName).append(" GROUP BY cst_id )").append(" ").append(tbAlias).append(" ON ").append("tm.vip_cst_id = ").append(tbAlias).append(".cst_id ");
                    continue;
                } else {
                    builder.append(" INNER JOIN ").append(tableName).append(" ").append(tbAlias).append(" ON ").append("tm.vip_cst_id = ").append(tbAlias).append(".cst_id ");
                }


                //查询条件
                List<TagProducer> tbProducers = tagsMap.get(conditionsClassEnumValue);
                for (int j = 0; j < tbProducers.size(); j++) {
                    TagProducer tbProducer = tbProducers.get(j);
                    StringBuilder whereBuilder = new StringBuilder();
                    if (tbProducer.getOrFlag() == 1) {
                        whereBuilder.append("(");
                        for (int k = 0; k < tbProducer.getOrList().size(); k++) {
                            TagProducerForOR forOR = tbProducer.getOrList().get(k);
                            if ((k != 0)) {
                                whereBuilder.append(" OR ");
                            }
                            whereBuilder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(forOR.getCompareStr()).append("'").append(forOR.getValue()).append("'");
                        }
                        whereBuilder.append(")");
                    } else {
                        if (tbProducer.getCompareStr().contains("IN")) {
                            whereBuilder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append(tbProducer.getValue());
                        } else {
                            whereBuilder.append(tbAlias).append(".").append(tbProducer.getColumnName()).append(tbProducer.getCompareStr()).append("'").append(tbProducer.getValue()).append("'");
                        }
                    }
                    whereList.add(String.valueOf(whereBuilder));
                }
            }
        }
        if (whereList.size() > 0 || tbMainFlag) {
            builder.append(" WHERE ");
            for (int s = 0; s < whereList.size(); s++) {
                if (s != 0) {
                    builder.append(" AND ");
                }
                builder.append(whereList.get(s));
            }
        }
        builder.append(" )");
        return builder.toString();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateTagHis(TagInfo t, Integer tagHisId, Integer status,Set<Long> deleteVipMap) {
        try {
            TagHis s = new TagHis();
            s.setId(tagHisId);
            s.setTagId(t.getId().intValue());
            s.setTagPeopleNumber(t.getTagPeopleNumber());
            s.setVersionStatus(status);
            s.setEndTime(new Date());
            tagHisDao.saveOrUpdate(s);
            if (status == 1) {
                //同步标签统计数据
                gradeToCouponService.syncTagStatistics(s);
                //同步标签会员数据
                gradeToCouponService.syncTagMember(s,deleteVipMap);
            }
        } catch (Exception e) {
            log.error("updateTagHis失败-----------{}" + e.getLocalizedMessage(), e);
            throw new BaseException("updateTagHis失败");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Integer addTagHis(TagInfo t) {
        try {
            TagHis s = new TagHis();
            s.setTagId(t.getId().intValue());
            s.setVersionStatus(t.getVersionStatus());
            s.setStartTime(new Date());
            tagHisDao.save(s);
            return s.getId();
        } catch (Exception e) {
            log.error("addTagHis失败-----------{}" + e.getLocalizedMessage(), e);
            throw new BaseException("addTagHis失败");
        }
    }

    public void syncToMarket(TagInfo tagInfo) {
        try {
            ArrayList<TagInfo> tagInfos = new ArrayList<>();
            TagInfo a = tagInfoDao.getById(tagInfo.getId());
            tagInfos.add(a);
            gradeToCouponService.sendToCouponTaggradeTagList(tagInfos);
        } catch (Exception e) {
            log.error("syncToMarket失败-----------{}" + e.getLocalizedMessage(), e);
        }
    }
}
